<?php
/**
 * 
 * 回调基础类
 * @author widyhu
 *
 */
class WxPayNotify extends WxPayNotifyReply
{
	/**
	 * 
	 * 回调入口
	 * @param bool $needSign  是否需要签名输出
	 */
	final public function Handle($needSign = true)
	{
	    \think\Log::info("handle");
		//当返回false的时候，表示notify中调用NotifyCallBack回调失败获取签名校验失败，此时直接回复失败
		$result = WxpayApi::notify(array($this, 'NotifyCallBack'), $msg);
		if($result == false){
			$this->SetReturn_code("FAIL");
			$this->SetReturn_msg($msg);
			$this->ReplyNotify(false);
			return;
		} else {
			//该分支在成功回调到NotifyCallBack方法，处理完成之后流程
			$this->SetReturn_code("SUCCESS");
			$this->SetReturn_msg("OK");
		}
		$this->ReplyNotify($needSign);
	}

    private function timeFormat($time){
        $paytime = substr($time,0,4).'-';
        $paytime .= substr($time,4,2).'-';
        $paytime .= substr($time,6,2);
        $paytime .= ' ';
        $paytime .= substr($time,8,2).':';
        $paytime .= substr($time,10,2).':';
        $paytime .= substr($time,12,2);
        $paytime = date('Y-m-d H:i:s',strtotime($paytime));
        return $paytime;
    }
/*
'appid' => 'wxb14592c898949839',
'attach' => 'test',
'bank_type' => 'CFT',
'cash_fee' => '1',
'fee_type' => 'CNY',
'is_subscribe' => 'N',
'mch_id' => '1489038592',
'nonce_str' => '7ut9nauwd2pxo91sjyp67apbxzweol2j',
'openid' => 'oUIQD0eg2MslS8JMrOX6tdy1kqgM',
'out_trade_no' => '5b03cd7a186759zIg8SwCK',
'result_code' => 'SUCCESS',
'return_code' => 'SUCCESS',
'sign' => 'AAEE1E0A8B234461CB7E5B12D33B339A',
'time_end' => '20180522155808',
'total_fee' => '1',
'trade_type' => 'NATIVE',
'transaction_id' => '4200000136201805226276596842',*/




    private function tryCatch($data){
        \think\Db::startTrans();
        try{

            //获取订单编号
            $orderNo = $data['out_trade_no'];
            //订单结束时间格式化
            $paytime = $this->timeFormat($data['time_end']);
            //修改充值状态
            $param['orderNo'] = $orderNo;
            $param['paytime'] = $paytime;
            $param['transaction_id'] = $data['transaction_id'];
            $param['total'] = $data['total_fee'];
            $this->updateServicebuyorder($param);
                \think\Db::commit();
                return true;
        }catch (Exception $e){
            \think\Db::rollback();

            return false;
        }
    }

    private function updateServicebuyorder($param){
        $servicebuyorderModel =  new   \app\admin\model\Servicebuyorder();
        $Servicebuyorder = $servicebuyorderModel->where('orderNo',$param['orderNo'])->find();
        $data['type'] = $Servicebuyorder->type;
        $data['tenantId'] = $Servicebuyorder->tenantId;
        $data['total'] = $param['total'];
        $Servicebuyorder->status = 1;
        $Servicebuyorder->total = $param['total'];
        $Servicebuyorder->transaction_id = $param['transaction_id'];
        $Servicebuyorder->updateDate = $param['paytime'];
        $Servicebuyorder->save();
        if($data['type'] == 1){
            \app\common\model\Tenant::where('id',$data['tenantId'])->setInc('balance',$data['total']);
        }else{
            \app\common\model\Tenant::where('id',$data['tenantId'])->setInc('dadaBalance',$data['total']);
        }
    }

	/**
	 * 
	 * 回调方法入口，子类可重写该方法
	 * 注意：
	 * 1、微信回调超时时间为2s，建议用户使用异步处理流程，确认成功之后立刻回复微信服务器
	 * 2、微信服务器在调用失败或者接到回包为非确认包的时候，会发起重试，需确保你的回调是可以重入
	 * @param array $data 回调解释出的参数
	 * @param string $msg 如果回调处理失败，可以将错误信息输出到该方法
	 * @return true回调出来完成不需要继续回调，false回调处理未完成需要继续回调
	 */
	public function NotifyProcess($data, &$msg)
	{
		//TODO 用户基础该类之后需要重写该方法，成功的时候返回true，失败返回false
        if($data['return_code'] == "SUCCESS" ){
            \think\Log::record("-----------------------++++++++++++++++",var_export($data,true));

            return $this->tryCatch($data);



        }else{



        }







		return true;
	}
	
	/**
	 * 
	 * notify回调方法，该方法中需要赋值需要输出的参数,不可重写
	 * @param array $data
	 * @return true回调出来完成不需要继续回调，false回调处理未完成需要继续回调
	 */
	final public function NotifyCallBack($data)
	{
		$msg = "OK";
		$result = $this->NotifyProcess($data, $msg);
		
		if($result == true){
			$this->SetReturn_code("SUCCESS");
			$this->SetReturn_msg("OK");
		} else {
			$this->SetReturn_code("FAIL");
			$this->SetReturn_msg($msg);
		}
		return $result;
	}
	
	/**
	 * 
	 * 回复通知
	 * @param bool $needSign 是否需要签名输出
	 */
	final private function ReplyNotify($needSign = true)
	{
		//如果需要签名
		if($needSign == true && 
			$this->GetReturn_code() == "SUCCESS")
		{
			$this->SetSign();
		}
		WxpayApi::replyNotify($this->ToXml());
	}
}